package risk.control.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import risk.control.application.entity.TransactionRecordBean;
import risk.control.application.http.HttpPostClient;
import risk.control.application.utils.DeviceUtils;
import risk.control.application.utils.data.TempCacheUtils;
import risk.control.application.utils.mmkv.MMKVUtils;


public class MainApplication extends Application {

    private static int activityCount = 0;

    //表单
    public static TransactionRecordBean transactionRecordBean = new TransactionRecordBean();

    @Override
    public void onCreate() {
        super.onCreate();
        if (transactionRecordBean == null) {
            transactionRecordBean = new TransactionRecordBean();
        }
        initListener();
        initSDK(this);
    }

    private void initSDK(Context context) {
        //1、mmkv
        MMKVUtils.init(context);
        //2、设备基本信息
        DeviceUtils.init(context);
    }

    private void initListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                activityCount++;
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                activityCount--;
                if (activityCount == 0) {
                    //所有Activity都已销毁应用即将退出
                    TempCacheUtils.getInstance().clearAll();
                    HttpPostClient.getInstance().cancelAll();
                }
            }
        });
    }
}

